#include <driver/ADC_driver.h>
#include <HAL/functionFactory.h>
#include <utitl/logger.h>

#include <boost/property_tree/ptree.hpp>

#include <stdlib.h>
#include <stdio.h>
#include <iostream>

using namespace ECG::Utitl;

namespace ECG
{

namespace HAL
{
    ADC_Driver::ADC_Driver():buf(NULL),len(0)
    {
        setID("AD8232");
    }

    ADC_Driver::~ADC_Driver()
    {
        if(!buf)
        {
            free(buf); 
        }

    }

    bool ADC_Driver::probe(DevicePtr device)
    {
        if(!device.get())
        {
            std::cout << "err, NULL device" << std::endl;
            return false;
        }
        this->device = device;
        // get fps
        fp = FuncFactory::instance()->getFuncByID(device->getFilterID());
        if(!fp.get())
        {
            std::cout << "err,fail to get fp,id = " << device->getFilterID() << std::endl;
            return false;
        }
        // get properties
        boost::property_tree::ptree hw = device->getHwConf();
        std::string bufLen = hw.get<std::string>("bufLen");
        if(bufLen.size())
        {
            len = atoi(bufLen.c_str());
            log_debug() << "buf len = " << len;
        }else
        {
            std::cout << "err,unable get buflen from hw" << std::endl;
            return false;
        }
        buf = (char*)malloc(len); // not forget free
        memset(buf,0,len);
        // configure HW
        iFd = fp->open(device->getDevPath().c_str());
        if(iFd < 0)
        {
            std::cout << "fail to open device:" <<device->getDevPath() << std::endl;
            return false;
        }
        if(fp->configure(iFd,hw))
        {
            log_debug() << "hw configure success...";
            return true;
        }else
        {
            std::cout << "error,fail to configure device" <<std::endl;
            return false;
        }
        
    }

    bool ADC_Driver::encode()
    {
        //read redis

        //call filter

        //write hw
        return true;
    }

    bool ADC_Driver::decode()
    {
        //read hw
        int ret;
        ret = fp->read(iFd,buf,len);
        if(ret <= 0)
        {
            std::cout << "fail to read iFd = " << iFd << std::endl;
            return false;
        }

        for(int i = 0 ;i< ret;i++)
        {
            printf("%x ",buf[i]&0xFF);
        }
        puts("recv buf");
        //call filter

        // write redis
        return true;
    }

    void ADC_Driver::start()
    {

    }

    void ADC_Driver::stop()
    {

    }

    registerDriver(ADC_Driver);
}

}